package com.iflytek.springboot_medicine.controller;

import com.iflytek.springboot_medicine.pojo.PageResultPojo;
import com.iflytek.springboot_medicine.pojo.ResponseMessage;
import com.iflytek.springboot_medicine.pojo.OrderPojo;
import com.iflytek.springboot_medicine.service.impl.OrderPojoServiceImpl;
import com.iflytek.springboot_medicine.service.impl.ShoppingServiceImpl;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/shop")
public class ShoppingController {

    private final ShoppingServiceImpl shoppingService;
    private final OrderPojoServiceImpl orderPojoService;

    public ShoppingController(ShoppingServiceImpl shoppingService, OrderPojoServiceImpl orderPojoService) {
        this.shoppingService = shoppingService;
        this.orderPojoService = orderPojoService;
    }

    @RequestMapping("/addShop")
    public ResponseMessage<OrderPojo> addShopping(@RequestBody OrderPojo orderPojo) {
        if (orderPojo == null) {
            return ResponseMessage.error("添加失败");
        }
        shoppingService.addShopping(orderPojo);
        return ResponseMessage.success(orderPojo);
    }

    @RequestMapping("/searchOrders")
    public ResponseMessage<PageResultPojo<OrderPojo>> searchShopping(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize
    ) {
        // 2. 调用 Service 层进行分页查询
        Page<OrderPojo> userPage = orderPojoService.findOrderPojo(pageNum, pageSize);
        // 3. 封装分页结果
        PageResultPojo<OrderPojo> pageResult = new PageResultPojo<>(
                userPage .getTotalElements(), // 总条数
                pageSize,                   // 每页条数
                pageNum,                    // 当前页码
                userPage .getContent()       // 当前页的数据
        );
        return ResponseMessage.success(pageResult);
    }

    /**
     * 删除订单
     * @param id
     * @return
     */
    @RequestMapping("/deleteShopCar/{id}")
    public ResponseMessage deleteShopCar(@PathVariable int id) {
        if (id > 0){
            orderPojoService.deleteOrderPojoById(id);
        }
        return ResponseMessage.success();
    }

    /**
     * 批量删除
     */
    @RequestMapping("/deleteBatchOrder")
    public ResponseMessage deleteBatchOrder(@RequestBody List<Integer> ids) {
        if (ids == null || ids.size() == 0) {
            return ResponseMessage.error("删除失败");
        }
        orderPojoService.deleteAllInBatch(ids);
        return ResponseMessage.success();
    }


}
